import { Component, ElementRef, EventEmitter, forwardRef, Input, OnChanges, Output, SimpleChanges, ViewChild, Optional, Inject } from "@angular/core";
import { ControlValueAccessor, NG_VALUE_ACCESSOR } from "@angular/forms";
import { FileUploader } from "ng2-file-upload";
import { MONK_FORMDEISGN_CONFIG, MonkFormDesignConfig } from "../../monk-form-design.interface";

@Component({
  selector: 'app-design-form-upload-custom',
  templateUrl: './design-form-upload-custom.component.html',
  styleUrls: ['./design-form-upload-custom.component.scss'],
  providers: [
    {
      provide: NG_VALUE_ACCESSOR,
      useExisting: forwardRef(() => DesignFormUploadCustomComponent),
      multi: true
    }
  ]

})
export class DesignFormUploadCustomComponent implements ControlValueAccessor, OnChanges {
  @ViewChild('inputFile') inputFile: ElementRef<HTMLInputElement>;
  @Input() record: any
  @Input() insideTable: boolean = false
  @Output() readonly previewOutput: EventEmitter<any> = new EventEmitter();
  public uploader: FileUploader
  _value
  _isDisabled = false
  constructor(
    @Optional() @Inject(MONK_FORMDEISGN_CONFIG) public config: MonkFormDesignConfig,
  ) {
  }

  initUpload() {
    this.uploader = new FileUploader({
      autoUpload: true,
      method: "POST",
      url: this.config?.fileUploadUrl || ''
    });
    this.uploader.onBeforeUploadItem = () => {
      //this.loading = true 
    }
    this.uploader.onAfterAddingFile = () => {
      //this.inputFile.nativeElement.value = '';
    }
    this.uploader.onSuccessItem = (event, res: any) => {
      //this.loading = false 
      if (res) {
        res = JSON.parse(res)
        res = this.config?.extractDataSuccess ? this.config.extractDataSuccess(res) : res;
        //if (!res.errorCode) {
          this._value = res
          this.onChange(res)
        //}
      }
    }
  }

  preview() {
    this.previewOutput.emit(this._value)
  }

  clear() {
    this._value = null
    this.onChange(null)
  }

  ngOnChanges(changes: SimpleChanges): void {
    this.initUpload()
  }  
  onChange: (_: any) => void = (_: any) => { };
  onTouched: () => void = () => { };
  writeValue(obj: any): void {
    //智治门户旧模板文件是数组，取第一个
    if (Array.isArray(obj) && obj[0]?.fileName && obj[0]?.storagePath) {
      this._value = obj[0]
    } else {
      this._value = obj
    }
  }
  registerOnChange(fn: any): void {
    this.onChange = fn
  }
  registerOnTouched(fn: any): void {
    this.onTouched = fn;
  }
  setDisabledState?(isDisabled: boolean): void {
    this._isDisabled = isDisabled
  }

  download() {
    this.config?.dataDownload(this._value?.storagePath)
  }
}
